<?php

namespace App\Http\Controllers;

use App\Http\Requests\BannerRequest;
use App\Models\Banner;
use App\Transformers\BannerTransformers;
use Illuminate\Http\Request;

class BannerController extends BaseController
{
    /**
     * 轮播图列表
     */
    public function index()
    {
        $banners=Banner::paginate(10);
        return $this->response->paginator($banners,new BannerTransformers());
    }

    /**
     * 添加
     */
    public function store(BannerRequest $request)
    {
        $max_sort=Banner::max('sort') ?? 0;
        $max_sort++;
        $request->offsetSet('sort',$max_sort);
        Banner::create($request->all());
//        return Banner::create($request->all());
        return $this->response->created();
    }

    /**
     * 详情
     */
    public function show(Banner $banner)
    {
        return $this->response->item($banner,new BannerTransformers());
    }

    /**
     * 更新
     */
    public function update(Request $request, Banner $banner)
    {
        $banner->update($request->all());
        return $this->response->noContent();
    }

    /**
     * 删除
     */
    public function destroy(Banner $banner)
    {
        $banner->delete();
        return $this->response->noContent();
    }

    /**
     * 排序
     */
    public function sort(Request $request,Banner $banner){
        $sort = $request ->input('sort');
        if (!is_numeric($sort) || $sort < 0){
            return $this->response->errorBadRequest('参数有误，请检查');
        }
        $banner->sort = $sort;
        $banner->save();
        return $this->response->noContent();
    }
}
